<template>
  <section>
    <div class="section-header">乙方供应商报工</div>
    <a-row :gutter="24">
      <a-col :span="8">
        <a-form-model-item label="节点报工：" prop="status">
          <div style="display: flex" class="col-input-2">
            <a-select
              v-model="task.partbStatus"
              :disabled="!checkPermission(['WORK_REPORT_MANAGER'])"
              @change="changeStatus"
            >
              <a-select-option
                v-for="(code, index) in codes.WorkReportResultStatus"
                :key="'status' + index"
                :value="code.code"
              >
                {{ code.name }}
              </a-select-option>
            </a-select>
            <a-select v-model="task.partbResult" :disabled="!checkPermission(['WORK_REPORT_MANAGER'])">
              <a-select-option
                v-for="(code, index) in codes.WorkReportResultType"
                :key="'result' + index"
                :value="code.code"
              >
                {{ code.name }}
              </a-select-option>
            </a-select>
          </div>
        </a-form-model-item>
      </a-col>
      <a-col :span="8">
        <a-form-model-item ref="actualTime" label="实际完成日期：" prop="actualTime">
          <a-date-picker
            valueFormat="YYYY-MM-DD"
            v-model="task.partbActualTime"
            clearable
            :disabled-date="disabledActualTimeDate"
            :disabled="!checkPermission(['WORK_REPORT_MANAGER'])"
          />
        </a-form-model-item>
      </a-col>
      <a-col :span="8">
        <a-form-model-item ref="projectName" label="预计完成日期：" prop="planTime">
          <a-date-picker
            valueFormat="YYYY-MM-DD"
            v-model="task.partbPlanTime"
            clearable
            :disabled-date="disabledPlanTimeDate"
            :disabled="!checkPermission(['WORK_REPORT_MANAGER'])"
          />
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row :gutter="24">
      <a-col :span="8">
        <a-form-model-item label="工期状态：" prop="nodeStatus">
          <div style="display: flex">
            <a-select disabled v-model="task.partbNodeStatus">
              <a-select-option
                v-for="(code, index) in codes.WorkReportNodeStatus"
                :key="'nodeStatus' + index"
                :value="code.code"
              >
                {{ code.name }}
              </a-select-option>
            </a-select>
            <a-input
              class="widthFull"
              style="width: 10vw; margin-left: 5px"
              v-if="task.partbNodeStatus == '逾期'"
              v-model="task.partbNodeDelayDays"
              suffix="天"
              disabled
            />
          </div>
        </a-form-model-item>
      </a-col>
      <a-col :span="8">
        <a-form-model-item label="逾期责任方：" prop="delayReason">
          <div style="display: flex" class="diyClass">
            <a-select
              v-model="task.partbDelayReason"
              :disabled="!checkPermission(['WORK_REPORT_MANAGER', '合同报工员']) && task.partbNodeStatus != '逾期'"
              allowClear
              @change="changeDelayReason"
            >
              <a-select-option
                v-for="(code, index) in codes.WorkReportDelayReson"
                :key="'delayReason' + index"
                :value="code.code"
              >
                {{ code.name }}
              </a-select-option>
            </a-select>
            <a-input
              v-if="task.partbDelayReason == '2'"
              v-model="task.partbDelayDays"
              addonBefore="乙方逾期"
              addonAfter="天"
            />
          </div>
        </a-form-model-item>
      </a-col>
      <a-col :span="8">
        <a-form-model-item ref="delayRemark" label="逾期具体原因：" prop="delayRemark">
          <a-select
            v-model="task.partbDelayRemark"
            :disabled="!checkPermission(['WORK_REPORT_MANAGER', '合同报工员']) && task.partbNodeStatus != '逾期'"
            allowClear
          >
            <a-select-option
              v-for="(code, index) in codes.WorkReportDelayRemarkFilter"
              :key="'delayRemark' + index"
              :value="code.code"
            >
              {{ code.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row :gutter="24">
      <a-col :span="16">
        <a-form-model-item label="补充说明：" prop="remark">
          <a-input :disabled="!checkPermission(['WORK_REPORT_MANAGER'])" v-model="task.partbRemark" />
        </a-form-model-item>
      </a-col>
      <a-col :span="8">
        <a-form-model-item ref="reportDate" label="乙方报工日期" prop="reportDate">
          <a-date-picker
            :disabled="!checkPermission(['WORK_REPORT_MANAGER'])"
            valueFormat="YYYY-MM-DD"
            v-model="task.partbReportDate"
          />
        </a-form-model-item>
      </a-col>
    </a-row>
    <div class="section-table">
      <div style="display: flex">
        <ht-upload
          v-if="
            (!task.partbIsCancleSubmit || task.partbIsCancleSubmit == '0' || task.partbIsCancleSubmit == '-1') &&
            checkPermission(['WORK_REPORT_MANAGER'])
          "
          ref="myUpload"
          class="upload-demo"
          dbKey="Trd"
          busField="workReport"
          busType="work_report_attach_b"
          :busKey="task.id + ''"
          ftpKey="ftp"
          v-model="fileList"
          :show-file-list="false"
          :before-upload="beforUpload"
          :on-success="afterUpload"
        >
          <a-button class="hte-btn add-btn" type="primary" icon="plus">新增附件</a-button>
        </ht-upload>
        <a-button @click="handleDownload()"> 下载 </a-button>
        <a-button @click="removeAttachRow()"> 删除 </a-button>
        <a-button
          type="link"
          @click="downloadResultTemplate('332b4423fcd54f41928dab1abbc5530b', '合同款项付款申请表（非基建）.doc')"
        >
          合同款项付款申请表（非基建）.doc
        </a-button>
        <a-button
          type="link"
          @click="downloadResultTemplate('83247339a397479eadb8f6a198ccf53d', '合同款项付款申请表（基建工程）.docx')"
        >
          合同款项付款申请表（基建工程）.docx
        </a-button>
      </div>
      <div>
        <a-table
          class="hte-table-content"
          :columns="columns"
          :data-source="records"
          :pagination="false"
          size="middle"
          rowKey="id"
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        >
          <span slot="action" slot-scope="text, record" style="display: flex">
            <a-button
              v-if="
                (!task.partbIsCancleSubmit || task.partbIsCancleSubmit == '0' || task.partbIsCancleSubmit == '-1') &&
                checkPermission(['WORK_REPORT_MANAGER'])
              "
              type="primary"
              size="small"
              @click="removeAttachRowByOne(record)"
              >删除</a-button
            >
          </span>
          <span slot="createTimeRender" slot-scope="text, record">
            <span v-if="record.createTime && record.createTime != '1900-01-01 00:00:00'">
              {{ record.createTime }}
            </span>
          </span>
          <span slot="index" slot-scope="text, record, index">
            {{ index + 1 }}
          </span>
          <span slot="previewRender" slot-scope="text, record">
            <span class="font-active" @click="handlePreview(record)">
              {{ record.fileName }}
            </span>
          </span>
        </a-table>
      </div>
    </div>
  </section>
</template>

<script>
import Vue from 'vue'
import { getAction, postAction, previewAttach } from '@/api/manage'
import { formatFileSize, endWith } from '@/utils/common.js'
import { calcDaysBetween } from '@/utils/util.js'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import '@/config/upload.install.js'
export default {
  props: {
    project: {
      type: Object,
      default: () => {
        return {}
      },
    },
    task: {
      type: Object,
      default: () => {
        return {}
      },
    },
    type: {
      type: String,
      default: '1',
    },
    permission: {
      type: Array,
      default: () => {
        return []
      },
    },
    currentHandlerUser: {
      type: String,
      default: null,
    },
  },
  data() {
    return {
      result: {},
      columns: [
        {
          title: '序号',
          scopedSlots: { customRender: 'index' },
        },
        {
          title: '文件名称',
          dataIndex: 'fileName',
          key: 'fileName',
          scopedSlots: { customRender: 'previewRender' },
        },
        {
          title: '文件大小',
          dataIndex: 'fileSize',
          key: 'fileSize',
        },
        {
          title: '上传人',
          dataIndex: 'createUser',
          key: 'createUser',
        },
        {
          title: '上传时间',
          dataIndex: 'createTime',
          key: 'createTime',
          scopedSlots: { customRender: 'createTimeRender' },
        },
        {
          title: '操作',
          scopedSlots: { customRender: 'action' },
        },
      ],
      records: [],
      urls: {
        attachs: '/workReport/attach/attachList',
        editAttach: '/workReport/attach/edit',
        deleteBetch: '/workReport/attach/deleteBetch',
        codes: '/manage/codeInfo/queryByTypes',
      },
      fileList: [],
      index: {},
      codes: {},
      currentSelection: [],
      selectedRowKeys: [],
    }
  },
  mounted() {
    this.fetchAttach()
    this.fetchCodes()
  },
  methods: {
    calcDaysBetween,
    disabledActualTimeDate(actualTime) {
      if (!actualTime) {
        return false
      }
      return actualTime.valueOf() >= new Date().valueOf()
    },
    disabledPlanTimeDate(planTime) {
      if (!planTime) {
        return false
      }
      return planTime.valueOf() < new Date().valueOf()
    },
    checkPermission(powers) {
      let hasPower = false
      for (let p of powers) {
        if (this.permission.indexOf(p) > -1) {
          hasPower = true
          break
        }
      }
      return hasPower
    },
    fetchCodes() {
      getAction(this.urls.codes, {
        types:
          'WorkReportResultType,WorkReportResultStatus,WorkReportDelayReson,WorkReportNodeStatus,WorkReportDelayRemark',
      }).then((res) => {
        if (res.success) {
          this.codes = { ...this.codes, ...res.result }
          this.$set(this.codes, 'WorkReportDelayRemarkFilter', this.codes.WorkReportDelayRemark)
          this.$set(this.codes, 'WorkReportResultTypeFilter', this.codes.WorkReportResultType)
          this.changeDelayReason()
        }
      })
    },
    fetchAttach() {
      getAction(
        this.urls.attachs + '?busType=work_report_attach_b' + '&busKey=' + encodeURIComponent(this.task.id),
        {}
      ).then((res) => {
        if (res.success) {
          this.records = res.result
        }
      })
    },
    addAttachRow() {
      this.records.push({ id: 0, busKey: '' })
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.currentSelection = selectedRows
    },
    removeAttachRow() {
      let record = this.currentSelection[0]
      if (this.currentSelection.length <= 0) {
        return this.$messageWorkReport.warning('请至少选择一个记录操作')
      }
      let ids = []
      this.currentSelection.forEach((s) => {
        if (s.id) {
          ids.push(s.id)
        }
      })
      if (ids.length <= 0) {
        return this.$messageWorkReport.warning('未找到附件记录')
      }
      if (ids.length > 0) {
        postAction(this.urls.deleteBetch + '?ids=' + ids.join(','), {}).then((res) => {
          if (res.success) {
            this.fetchAttach()
          } else {
            this.$messageWorkReport.error(res.message)
          }
        })
      }
    },
    removeAttachRowByOne(record) {
      if (record.id) {
        postAction(this.urls.deleteBetch + '?ids=' + record.id, {}).then((res) => {
          if (res.success) {
            this.fetchAttach()
          } else {
            this.$messageWorkReport.error(res.message)
          }
        })
      } else {
        return this.$messageWorkReport.warning('未找到附件记录')
      }
    },
    clearAttach(index) {
      let record = this.records[index]
      if (record.id) {
        postAction(this.urls.clearAttach + '/' + record.id, {}).then((res) => {
          if (res.success) {
            this.fetchAttach()
          } else {
            this.$messageWorkReport.error(res.message)
          }
        })
      }
    },
    handleDownload() {
      if (this.currentSelection.length == 1) {
        let record = this.currentSelection[0]
        if (record.busFk) {
          const token = Vue.ls.get(ACCESS_TOKEN)
          window.open(
            process.env.VUE_APP_API_BASE_URL + '/workReport/attach/download?token=' + token + '&id=' + record.busFk
          )
        }
      } else if (this.currentSelection.length > 1) {
        let ids = []
        this.currentSelection.forEach((r) => {
          ids.push(r.busFk)
        })
        let tempFileName = this.project.contractNumber + '#' + this.project.contractName + '#乙方.zip'

        const token = Vue.ls.get(ACCESS_TOKEN)
        var href =
          this.API_BASE_URL +
          '/common/downLoadBatchWithFileName?attachIds=' +
          ids.join(',') +
          '&dbKey=Trd&ftpKey=ftp&token=' +
          this.$ls.get(ACCESS_TOKEN) +
          '&zipFileName=' +
          encodeURIComponent(tempFileName)

        this.doDownLoadByIframe(href)
      }
    },
    handlePreview(file) {
      let that = this
      if (
        endWith(file.fileName, 'rar') ||
        endWith(file.fileName, 'zip') ||
        endWith(file.fileName, 'dwg') ||
        endWith(file.fileName, 'tgz')
      ) {
        return true
      }
      let params = {
        id: file.busFk,
        ftpKey: 'ftp',
      }
      previewAttach(params)
        .then((result) => {
          const url = URL.createObjectURL(result)
          window.open(process.env.BASE_URL + '/pdf/web/viewer.html?file=' + url)
        })
        .catch((err) => {
          this.$messageWorkReport.warning('下载文件失败')
        })
    },
    beforUpload(index) {
      this.index = index
    },
    afterUpload(response) {
      let record = {} //this.records[this.index]
      if (response && response.length > 0) {
        this.$set(record, 'fileName', response[0].fileName)
        this.$set(record, 'filePath', response[0].path)
        this.$set(record, 'fileSize', response[0].size)
        this.$set(record, 'createUser', response[0].uploaderName)
        this.$set(record, 'createUserId', response[0].uploader)
        this.$set(record, 'createTime', response[0].uploadTime)
        this.$set(record, 'busType', response[0].busType)
        this.$set(record, 'busKey', this.task.id)
        this.$set(record, 'busFk', response[0].id)
        this.$set(record, 'platForm', 'HTE')
        postAction(this.urls.editAttach, record).then((res) => {
          if (res.success) {
            this.fetchAttach()
          } else {
            this.$messageWorkReport.error(res.message)
          }
        })
      }
    },
    changeDelayReason() {
      let delayRemark = ''
      if (this.codes.WorkReportDelayRemark) {
        this.codes.WorkReportDelayRemark.forEach((item) => {
          if (item.code == this.task.partbDelayRemark) {
            delayRemark = item.name
          }
        })
      }

      let delayReson = ''
      if (this.codes.WorkReportDelayReson) {
        this.codes.WorkReportDelayReson.forEach((item) => {
          if (item.code == this.task.partbDelayReason) {
            delayReson = item.name
          }
        })
      }
      let WorkReportDelayRemarkFilter = []
      if (this.codes.WorkReportDelayRemark) {
        this.codes.WorkReportDelayRemark.forEach((item) => {
          if (item.name.startsWith(delayReson)) {
            WorkReportDelayRemarkFilter.push(item)
          }
        })
      }
      this.$set(this.codes, 'WorkReportDelayRemarkFilter', WorkReportDelayRemarkFilter)
      if (this.task.partbDelayRemark && !delayRemark.startsWith(delayReson)) {
        this.$set(this.task, 'partbDelayRemark', '')
      } else {
        return
      }
    },
    changeStatus() {
      let WorkReportResultTypeFilter = []
      if (this.task.partbStatus != '2') {
        if (this.task.partbResult == '质量合格') {
          this.$set(this.task, 'partbResult', '')
        }
        this.codes.WorkReportResultType.forEach((code) => {
          if (code.name != '质量合格') {
            WorkReportResultTypeFilter.push(code)
          }
        })
        this.$set(this.codes, 'WorkReportResultTypeFilter', WorkReportResultTypeFilter)
      } else {
        this.$set(this.codes, 'WorkReportResultTypeFilter', this.codes.WorkReportResultType)
      }
    },
    downloadResultTemplate(id, fileName) {
      let url =
        process.env.VUE_APP_API_BASE_URL +
        '/ps/workReport/downloadResultTemplate?id=' +
        id +
        '&taskId=' +
        this.task.id +
        '&fileName=' +
        encodeURIComponent(this.project.contractName + '#' + this.project.contractNumber + '#' + fileName) +
        '&userName=' +
        this.$store.getters.userInfo.realname
      window.open(url)
    },
    doDownLoadByIframe(url) {
      if (document.getElementById('_attachToolView_downloadfile_frame') == null) {
        var downloadFrame = $('<iframe id="_attachToolView_downloadfile_frame" style="display: none"></iframe>')
        downloadFrame.appendTo($('body'))
      }
      var iframe = document.getElementById('_attachToolView_downloadfile_frame')
      iframe.src = url
    },
  },
  watch: {
    task: {
      handler(newV, oldV) {
        let endTime = new Date()
        if (this.task.partbStatus == '2') {
          endTime = this.task.partbActualTime ? this.task.partbActualTime + ' 23:59:59.999' : ''
        }
        let temp = this.calcDaysBetween(this.task.complateTime + ' 23:59:59.999', endTime)
        this.$set(this.task, 'partbNodeStatus', temp.status)
        if (temp.status != '正常') {
          this.$set(this.task, 'partbNodeDelayDays', temp.days)
        } else {
          this.$set(this.task, 'partbNodeDelayDays', 0)
        }
        if (newV && newV.id && (!oldV || !oldV.id)) {
          this.fetchAttach()
        }
        if(this.task.partbNodeStatus=="正常"){
          // this.$set(this.task, 'partbDelayReason', "")
          // this.$set(this.task, 'partbDelayRemark', "")
        }
        this.$emit('update:task', this.task)
      },

      deep: true,
      immediate: true,
    },
  },
}
</script>

<style lang="less" scoped>
@import '~@assets/less/hte-main.less';
section {
  margin-bottom: 18px;
  .section-table {
    margin-top: 30px;
    .add-btn {
      margin-left: 0;
      margin-bottom: 10px;
    }
    /deep/ .el-upload__input {
      display: none !important;
    }
  }
  .redText {
    color: red;
  }
}
.diyClass /deep/.ant-input {
  padding: 0 3px;
}
.diyClass /deep/.ant-input-group-addon {
  padding: 0 3px;
}
.widthFull /deep/.ant-input {
  width: 100%;
}
</style>
